/**
 * 
 */
package org.dragonfire.dasm.directives;

import java.util.ArrayList;

import org.dragonfire.dasm.Command;
import org.dragonfire.dasm.CompileException;
import org.dragonfire.dasm.DASM;
import org.dragonfire.dasm.Listing;
import org.dragonfire.dasm.DirectiveManager.Directive;
import org.dragonfire.dasm.instr.Macro;
import org.dragonfire.util.DString;

import com.stevesoft.pat.Regex;

/**
 * @author Darth Android
 * @date Jun 9, 2007
 */
// TODO finish documentation
public class Definternal extends Directive {

	String lastDefined = null;
	String lastModule = null;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ArrayList<Listing> pass1(Command c) {
		String cmd = evalString(c.getParam(0)).toLowerCase();
		if (c.getParams().length == 3 && cmd.equals("define")) {
			String name = evalString(c.getParam(1));
			if (name.matches(DASM.LABEL_REGEX + "\\(.*\\)")) {
				String[] macroArgs = null;
				Regex r = new Regex("(" + DASM.LABEL_REGEX + ")\\((.*)\\)");
				r.search(name);
				macroArgs = DString.splitTopLevel(r.stringMatched(3), ',');
				name = r.stringMatched(1);
				Macro m = new Macro(name, macroArgs, new String[] {
					c.getParam(2)
				});
				getCompiler().getInstructions().addCommand(m);
			}
			else if (Regex.matches(DASM.LABEL_REGEX, name)) {
				getCompiler().define(name, getPreprocessor().getCurrentModule(), c.getParam(2));
				lastDefined = name;
				lastModule = getPreprocessor().getCurrentModule();
			}
			else
				throw new CompileException("ERROR_INVALID_LABEL", name);
		}
		else if (cmd.equals("continue")) {
			if (lastDefined == null)
				throw new CompileException("ERROR_DEFINE_NOT_YET_USED");
			getCompiler().define(lastDefined, lastModule,
					getCompiler().getDefine(lastDefined, lastModule) + " " + c.getParam(1));
		}
		return null;
	}
}
